package com.example.ws.handler.elog;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Path;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class LocalLogFileObserver extends FileAlterationListenerAdaptor {
    public static final LocalLogFileObserver instance = new LocalLogFileObserver();

    private long pos = 0;

    private RandomAccessFile reader;

    private LocalLogFileObserver() {
    }

    public static LocalLogFileObserver getInstance() {
        return instance;
    }

    public void init(String target, long interval) {
        File targetFile = new File(target);
        FileAlterationObserver fileObserver = new FileAlterationObserver(targetFile);
        fileObserver.addListener(instance);
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval, fileObserver);
        try {
            monitor.start();
            reader = new RandomAccessFile(targetFile, "r");
            reader.seek(0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onFileChange(File file) {
        LocalELogCache.getInstance().addAll(null);
    }

    public String lastestLines() {
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            reader.seek(pos);
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
                pos = reader.getFilePointer();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
